import '../../public.dart'; // 这样会导入dart:io和其他必要的包
import 'package:image_picker/image_picker.dart';

class ImageUploadWidget extends StatefulWidget {
  final List<File> images;
  final Function(File) onImageAdded;
  final Function(int) onImageRemoved;
  final int maxImages;

  const ImageUploadWidget({
    super.key,
    required this.images,
    required this.onImageAdded,
    required this.onImageRemoved,
    this.maxImages = 9,
  });

  @override
  State<ImageUploadWidget> createState() => _ImageUploadWidgetState();
}

class _ImageUploadWidgetState extends State<ImageUploadWidget> {
  bool _isUploading = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Upload card image',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 8),
        _buildImageGrid(),
      ],
    );
  }

  Widget _buildImageGrid() {
    // 显示已上传的图片和上传按钮
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 8,
        mainAxisSpacing: 8,
        childAspectRatio: 1.0,
      ),
      itemCount: widget.images.length < widget.maxImages
          ? widget.images.length + 1
          : widget.images.length,
      itemBuilder: (context, index) {
        if (index == widget.images.length &&
            widget.images.length < widget.maxImages) {
          // 上传按钮
          return _buildUploadButton();
        } else {
          // 已上传的图片
          return _buildImageItem(widget.images[index], index);
        }
      },
    );
  }

  Widget _buildUploadButton() {
    return InkWell(
      onTap: _showImagePickerOptions,
      borderRadius: BorderRadius.circular(8.0),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0),
          border: Border.all(
            color: Colors.grey.shade300,
            width: 1.0,
            style: BorderStyle.solid,
          ),
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _isUploading
                ? const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(),
                  )
                : const Icon(Icons.upload, color: Colors.grey),
            const SizedBox(height: 4),
            Text(
              _isUploading ? 'Uploading...' : 'Upload image(s)',
              style: const TextStyle(color: Colors.grey),
              textAlign: TextAlign.center,
              maxLines: 1,
            ),
            Text(
              '${widget.images.length}/${widget.maxImages}',
              style: const TextStyle(color: Colors.grey, fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageItem(File image, int index) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: Image.file(
            image,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
        ),
        Positioned(
          top: 4,
          right: 4,
          child: InkWell(
            onTap: () => widget.onImageRemoved(index),
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
              ),
              padding: const EdgeInsets.all(4),
              child: const Icon(Icons.delete, color: Colors.white, size: 16),
            ),
          ),
        ),
      ],
    );
  }

  // 处理图片选择，使用image_picker库
  void _showImagePickerOptions() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('Capture with Camera'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('Select from Gallery'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.gallery);
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('Cancel'),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  // 使用image_picker选择图片
  Future<void> _pickImage(ImageSource source) async {
    try {
      setState(() {
        _isUploading = true;
      });

      final picker = ImagePicker();
      final pickedFile = await picker.pickImage(
        source: source,
        imageQuality: 80, // 图片质量，0-100
        maxWidth: 1024,
        maxHeight: 1024,
      );

      if (pickedFile != null) {
        final imageFile = File(pickedFile.path);
        widget.onImageAdded(imageFile);
      }
    } catch (e) {
      // 处理错误
      Toast.show('图片选择错误: $e');
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }
}
